<template>
	<view class="container">
			<checkbox-group @change="handleStudentCourseCheckboxChange">
		<!-- 输入表单 -->
		<view v-if="currentLevel === 0">
			<view v-if="!isFormCollapsed" class="form-container">
				<view class="form-item">
					<label>姓名</label>
					<input v-model="formData.name" placeholder="请输入姓名" />
				</view>
				<view class="form-item">
					<label>手机号</label>
					<input v-model="formData.phoneNumber" placeholder="请输入手机号" />
				</view>
				<view class="form-item">
					<label>年龄</label>
					<input v-model="formData.age" placeholder="请输入年龄" />
				</view>
				<view class="form-item">
					<label>职业</label>
					<picker v-model="formData.occupation" :range="occupations" @change="onOccupations">
						<view class="picker">
							{{ formData.occupation || '请选择职业' }}
						</view>
					</picker>
				</view>
				<view class="form-item">
					<label>地区</label>
					<picker mode="region" v-model="formData.address" @change="onRegionChange">
						<view class="picker">
							{{ formData.address.length > 0? formData.address.join(' ') : '请选择地区' }}
						</view>
					</picker>
				</view>
				<view class="form-item">
					<label>营期</label>
					<picker v-model="formData.currentSessionNumber" :range="sessionNumberOptions" @change="onSession">
						<view class="picker">
							{{ formData.currentSessionNumber || '请选择营期' }}
						</view>
					</picker>
				</view>
				<view class="form-item">
					<label>班级</label>
					<picker v-model="formData.classId" :range="classOptions" range-key="name" @change="onClassChange">
						<view class="picker">
							{{ getSelectedClassName() || '请选择班级' }}
						</view>
					</picker>
				</view>
				<view class="form-item">
					<label>大组</label>
					<picker v-model="formData.largeGroupId" :range="largeGroupsOptions" range-key="name"
						@change="onLargeGroupChange" :disabled="formData.classId == ''">
						<view class="picker">
							{{ getSelectedtLargeGroupName() || '请选择大组' }}
						</view>
					</picker>
				</view>
				<view class="form-item">
					<label>小组</label>
					<picker v-model="formData.smallGroupId" :range="smallGroupsOptions" range-key="name"
						@change="onSmallGroupChange" :disabled="formData.largeGroupId == ''">
						<view class="picker">
							{{ getSelectedSmallGroupName() || '请选择小组' }}
						</view>
					</picker>
				</view>
				<button @click="fetchStudents" style="width: 50%; float: left;">搜索</button>
				<button @click="cleanForm" style="width: 50%; float: left;">清空</button>
			</view>
			<!-- 展开/收起表单按钮 -->
			<button @click="toggleForm">{{ isFormCollapsed? '展开' : '收起' }}</button>
			<button @click="goSetClass">升班</button>
		</view>
		<!-- 奖励列表 -->
		<view v-if="currentLevel === 1" class="course-list">
			<view v-for="(award, index) in awards" :key="index" class="award-item" @click="confirmAward(award)">
				{{ award }}
			</view>
		</view>
		<!-- 学生信息列表 -->
		<view class="student-list">
				<view v-for="student in students" :key="student.students.id" class="student-item">
					<view class="student-info">
						<view>{{ student.students.name }}</view>
						<view>{{ student.students.age == null? '' : student.students.age }}</view>
						<view>{{ student.students.phoneNumber == null? '' : student.students.phoneNumber }}</view>
					</view>
					<view class="student-info">
						<view>{{ student.students.address == null? '' : student.students.address }}</view>
						<view>{{ student.students.occupation == null? '' : student.students.occupation }}</view>
					</view>
					<view v-if="student.studentCourses.length > 0" class="student-info">
						<view v-for="(course, courseIndex) in student.studentCourses" :key="courseIndex">
							<checkbox :value="JSON.stringify(course)" style="float: right;"></checkbox>
							<view>{{ course.currentSessionNumber}}期 - {{course.className}} - {{course.largeGroupName}} -
								{{course.smallGroupName}}
							</view>
						</view>
					</view>
				</view>
			
		</view>
		<!-- 返回按钮 -->
		<button v-if="currentLevel > 0" @click="goBack">返回</button>
		</checkbox-group>
	</view>
</template>

<script>
	export default {
		data() {
			return {
				students: [],
				currentLevel: 0,
				classList: [{
						id: 1,
						name: '格物班'
					},
					{
						id: 2,
						name: '致知班'
					},
					{
						id: 3,
						name: '正心班'
					},
					{
						id: 4,
						name: '诚意班'
					}
				],
				classOptions: [{
						id: 1,
						name: '格物班'
					},
					{
						id: 2,
						name: '致知班'
					},
					{
						id: 3,
						name: '正心班'
					},
					{
						id: 4,
						name: '诚意班'
					}
				],
				sessionNumberOptions: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12],
				sessionList: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12],
				largeGroupsOptions: [],
				smallGroupsOptions: [],
				largeGroupList: [],
				smallGroupList: [],
				selectedStudentIds: [],
				selectedSessionId: null,
				selectedClassId: null,
				selectedLargeGroupId: null,
				occupations: ['农、林、牧、渔业', '采矿业', '制造业', '电力、热力、燃气及水生产和供应业', '建筑业', '批发和零售业', '交通运输、仓储和邮政业',
					'住宿和餐饮业 ', '信息传输、软件和信息技术服务业', '金融业', '房地产业', '租赁和商务服务业', '科学研究和技术服务业',
					'水利、环境和公共设施管理业', '居民服务、修理和其他服务业', '教育', '卫生和社会工作 ', '文化、体育和娱乐业 ', '公共管理、社会保障和社会组织',
					'国际组织', '学生', '其他'
				],
				formData: {
					address: [],
					occupation: '',
					name: '',
					phoneNumber: '',
					age: '',
					currentSessionNumber: '',
					classId: '',
					largeGroupId: '',
					smallGroupId: ''
				},
				isFormCollapsed: false,
				awards: ['优秀标兵', '高能引领奖', '优秀功课奖', '高能引领奖', '前置引领奖'],
				selectedStudentCourse: [] // 用于存储每个学生选中的studentCourses的id
			};
		},
		onLoad() {
			this.fetchStudents();
		},
		methods: {
			onSession(e) {
				this.formData.currentSessionNumber = this.sessionNumberOptions[e.detail.value]
			},
			onClassChange(e) {
				const selectedIndex = e.detail.value; 
				this.formData.classId = this.classOptions[selectedIndex].id;
				console.log(this.classOptions[selectedIndex].id)
				this.formData.largeGroupId = ''
				this.formData.smallGroupId = ''
				uni.request({
					url: 'http://localhost:9090/user/getResource',
					method: 'POST',
					data: {
						parentId: this.formData.classId,
						level: 2
					},
					success: (res) => {
						this.largeGroupsOptions = res.data.data
					},
					fail: (err) => {
						console.error('获取资源失败:', err);
					}
				});
			},
			getSelectedClassName() {
				const selectedOption = this.classOptions.find(item => item.id === this.formData.classId);
				return selectedOption ? selectedOption.name : null;
			},
			onLargeGroupChange(e) {
			
				this.formData.largeGroupId = this.largeGroupsOptions[e.detail.value].id
				this.formData.smallGroupId = ''
				uni.request({
					url: 'http://localhost:9090/user/getResource',
					method: 'POST',
					data: {
						parentId: this.formData.largeGroupId,
						level: 3
					},
					success: (res) => {
						this.smallGroupsOptions = res.data.data
					},
					fail: (err) => {
						console.error('获取资源失败:', err);
					}
				});
			},
			getSelectedtLargeGroupName() {
				  
				try{
					const selectedOption= this.largeGroupsOptions.find(item => item.id === this.formData.largeGroupId.toString());
						return selectedOption ? selectedOption.name : null;
				}catch(e){
					this.cleanForm()
				}
				
				
				return selectedOption ? selectedOption.name : null;
			},
			onSmallGroupChange(e) {
				this.formData.smallGroupId = this.smallGroupsOptions[e.detail.value].id
			},
			getSelectedSmallGroupName() {
				const selectedOption = this.smallGroupsOptions.find(item => item.id === this.formData.smallGroupId
					.toString());
				return selectedOption ? selectedOption.name : null;
			},
			// 获取学生信息
			fetchStudents() {
				this.students = []
				uni.request({
					url: 'http://localhost:9090/user/getStudents2',
					method: 'POST',
					data: {
						name: this.formData.name,
						phoneNumber: this.formData.phoneNumber,
						occupation: this.formData.occupation,
						age: this.formData.age,
						address: this.formData.address.toString(),
						currentSessionNumber: this.formData.currentSessionNumber,
						classId: this.formData.classId,
						largeGroupId: this.formData.largeGroupId,
						smallGroupId: this.formData.smallGroupId
					},
					success: (res) => {
						this.selectedStudentIds = []
						this.students = res.data.data;
					},
					fail: (err) => {
						console.error('获取学生信息失败:', err);
					}
				});
			},
			addIds(studentId) {
				const index = this.selectedStudentIds.indexOf(studentId);
				if (index > -1) {
					// 如果存在，从数组中移除
					this.selectedStudentIds.splice(index, 1);
				} else {
					// 如果不存在，添加到数组中
					this.selectedStudentIds.push(studentId);
				}
			},
			// 进入设置页面
			goToSettings() {
				// 这里可以根据需求做更多处理，比如将选中的学生 ID 传递给后续操作
				this.currentLevel = 1;
			},
			goSetClass() {
				if (this.selectedStudentCourse.length === 0) {
				return	uni.showToast({
						title: '请先选择',
						icon: 'none'
					});
				} else if (this.selectedStudentCourse.length > 1) {
					return	uni.showToast({
							title: '不能选择多个',
							icon: 'none'
						});
				}else{
					let params = JSON.parse(this.selectedStudentCourse)
					console.log(params)
					if(params.classId ==='4'){
						return uni.showToast({
							title: '诚意班已无法继续升班',
							icon: 'none'
						});
					}
					uni.request({
						url: 'http://localhost:9090/course/signUp2',
						method: 'POST',
						data: {
							classId: Number(params.classId) + 1,
							currentSessionNumber: params.currentSessionNumber,
							studentId: uni.getStorageSync('userInfo').id
						},
						success: (res) => {
							uni.showToast({
								title: res.data.data,
								icon: 'none'
							});
							this.fetchStudents()
						},
						fail: (err) => {
							console.error('请求失败', err);
						}
					});
				}
			},
			cleanForm() {
				this.formData = {
					address: [],
					occupation: '',
					name: '',
					phoneNumber: '',
					age: '',
					currentSessionNumber: '',
					classId: '',
					largeGroupId: '',
					smallGroupId: ''
				}
				this.largeGroupsOptions = []
				this.smallGroupsOptions = []
			},
			// 进入班级列表
			async goToClassList(sessionId) {
				this.selectedSessionId = sessionId;
				this.currentLevel = 2;
			},
			checkboxChange(e) {
				this.selectedStudentIds = e.detail.value
			},
			handleStudentCourseCheckboxChange(e) {
				this.selectedStudentCourse = e.detail.value;
			},
			// 进入大组列表
			async goToLargeGroupList(classId) {
				this.selectedClassId = classId;
				this.getResource(classId, 2);
				this.currentLevel = 3;
			},
			// 进入小组列表
			async goToSmallGroupList(largeGroupId) {
				this.selectedLargeGroupId = largeGroupId;
				this.getResource(largeGroupId, 3);
				this.currentLevel = 4;
			},
			// 根据id获取课程信息
			getCourseById(id) {
				return this.courseList.find(item => item.id === id);
			},
			// 根据id获取班级信息
			getClassById(id) {
				return this.classList.find(item => item.id === id);
			},
			// 根据id获取大组信息
			getLargeGroupById(id) {
				return this.largeGroupList.find(item => item.id === id);
			},
			// 返回上一层
			goBack() {
				this.selectedStudentIds = []
				this.currentLevel--;
			},
			// 获取资源
			getResource(parentId, level) {
				uni.request({
					url: 'http://localhost:9090/user/getResource',
					method: 'POST',
					data: {
						parentId,
						level
					},
					success: (res) => {
						if (level === 1) {
							this.classList = res.data.data;
						} else if (level === 2) {
							this.largeGroupList = res.data.data;
						} else {
							this.smallGroupList = res.data.data;
						}
					},
					fail: (err) => {
						console.error('获取资源失败:', err);
					}
				});
			},
			// 地区选择器改变事件
			onRegionChange(e) {
				this.formData.address = e.detail.value;
				this.$forceUpdate();
			},
			onOccupations(e) {
				this.formData.occupation = this.occupations[e.detail.value];
			},
			// 展开/收起表单
			toggleForm() {
				this.isFormCollapsed = !this.isFormCollapsed;
			},
			confirmAward(award) {
				uni.showModal({
					title: '确认',
					content: `是否确认选择奖励：${award}？`,
					success: (res) => {
						let awardRecords = []
						for (var i = 0; i < this.selectedStudentCourse.length; i++) {
							awardRecords.push(JSON.parse(this.selectedStudentCourse[i]))
						}
						let id = uni.getStorageSync('userInfo').id
						uni.request({
							url: 'http://localhost:9090/user/setAward',
							method: 'POST',
							data: {
								awardRecords,
								award,
								id
							},
							success: (res) => {
								this.largeGroupsOptions = res.data.data
							},
							fail: (err) => {
								console.error('获取资源失败:', err);
							}
						});
						this.currentLevel = 0;
						this.cleanForm();
						this.fetchStudents();
					}
				});
			}
		}
	};
</script>

<style scoped>
	.container {
		padding: 20px;
	}

	.form-container {
		margin-bottom: 20px;
	}

	.form-item {
		display: flex;
		align-items: center;
		margin-bottom: 10px;
	}

	.form-item label {
		width: 80px;
	}

	input {
		flex: 1;
		padding: 10px;
		border: 1px solid #ccc;
		margin-right: 10px;
	}

	button {
		padding: 10px 20px;
		margin-bottom: 10px;
	}

	.student-list,
	.course-list,
	.class-list,
	.large-group-list,
	.small-group-list {
		margin-top: 20px;
	}

	.student-item {
		padding: 10px;
		border: 1px solid #ccc;
		margin-bottom: 10px;
		align-items: center;
	}

.student-info {
    display: flex;
    flex-direction: column;
    justify-content: space-around;
    flex: 1;
}
	.course-item,
	.class-item,
	.large-group-item,
	.small-group-item {
		padding: 10px;
		border: 1px solid #ccc;
		margin-bottom: 10px;
		cursor: pointer;
	}
</style>